<?php
// +----------------------------------------------------------------------
// | XiaMiCMF - 代码如诗
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://shujuwajue.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小虾米 <509129@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Common\Controller\AdminBaseController;

class MenuController extends AdminBaseController
{
    const CNAME = '菜单';

    protected $menu_model;
    protected $authRule_model;

    public function _initialize() {
        parent::_initialize();
        $this->menu_model     = D("Menu");
        $this->authRule_model = M("AuthRule");
        $this->assign('TITLE', self::CNAME);
    }

    /**
     * 菜单列表
     */
    public function index() {
        $menus = $this->_getMenuTree();
        foreach($menus as $_k => $_v ){
            $menus[$_k]['app'] =$_v['app']."/".$_v['controller']."/".$_v['action'];
        }
        $this->assign('menus', $menus);
        $this->display();
    }

    /**
     * 添加菜单
     */
    public function add() {
        if (IS_POST) {
            $data = $this->menu_model->create();
            if ($data) {
                $id = $this->menu_model->add($data);
                if ($id) {
                    $app        = I("post.app");
                    $controller = I("post.controller");
                    $action     = I("post.action");
                    $name       = strtolower("$app/$controller/$action");
                    $menu_name  = I("post.menu_name");
                    $where      = array("name" => $name);
                    $rule_count = $this->authRule_model->where($where)->count();
                    if (empty($rule_count)) {
                        $rule_id = $this->authRule_model->add(array(
                            "name"      => $name,
                            "module"    => $app,
                            "type"      => "admin_url",
                            "rule_name" => $menu_name
                        ));
                        $this->menu_model->where(array('menu_id' => $id))->save(array('rule_id' => $rule_id));
                    }

                    $this->success('添加成功', U('index'));
                } else {
                    $this->error('添加失败');
                }
            } else {
                $this->error($this->menu_model->getError());
            }
        } else {
            $menu_pid = I('get.parent_id', 0, 'intval');
            $menus = $this->_getMenuTree();
            $this->assign('menus', $menus);
            $this->assign('parent_id', $menu_pid);
            $this->display();
        }
    }

    /**
     * 编辑菜单
     */
    public function edit() {

        $menu_id = I('menu_id', 0, 'intval');
        $detail = $this->menu_model->find($menu_id);

        if (!$detail) {
            $this->error('请选择要编辑的' . self::CNAME);
        }

        if (IS_POST) {
            $data = $this->menu_model->create();
            if ($data) {
                if ($this->menu_model->save($data) !== false) {

                    $app        = I("post.app");
                    $controller = I("post.controller");
                    $action     = I('post.action');
                    $name       = strtolower("$app/$controller/$action");
                    $menu_name  = I('post.menu_name');
                    $where      = array('rule_id' => $detail['rule_id']);

                    $rule_count = $this->authRule_model->where($where)->count();
                    if(empty($rule_count)){
                        $id = $this->authRule_model->add(array(
                            'name'      => $name,
                            'module'    => $app,
                            'type'      => 'admin_url',
                            'rule_name' => $menu_name));
                        $this->menu_model->where(array('menu_id' => $id))
                             ->save(array('rule_id' => $detail['rule_id']));
                    } else {
                        $this->authRule_model->where($where)->save(array(
                            "name"      => $name,
                            "module"    => $app,
                            "type"      => "admin_url",
                            "rule_name" => $menu_name
                        ));
                    }
                    $this->success('编辑成功', U('index'));
                } else {
                    $this->error('编辑失败');
                }
            } else {
                $this->error($this->menu_model->getError());
            }
        } else {
            $menus = $this->_getMenuTree();
            $this->assign('menus', $menus);
            $this->assign('detail', $detail);
            $this->display();
        }
    }

    /**
     * 删除菜单
     */
    public function delete() {
        $menu_id = I('post.menu_id', 0, 'intval');
        if (is_numeric($menu_id)) {
            $menus = $this->menu_model->fetchAll();
            foreach ($menus as $menu) {
                if ($menu['parent_id'] == $menu_id)
                    $this->error('该菜单下还有其他子菜单,请先删除子菜单');
            }
            $this->menu_model->delete($menu_id);
            $this->success('删除成功', U('index'));
        } else {
            $this->error('请选择要删除的' . self::CNAME);
        }
    }

    /**
     * 更新菜单排序
     */
    public function updateSort() {
        $status = parent::_updateListSort($this->menu_model);
        if ($status) {
            $this->success("更新排序成功", U('index'));
        } else {
            $this->error("更新排序失败");
        }
    }

    /**
     * 启用或禁用菜单
     */
    public function changeStatus() {

        $menu_id = I('post.menu_id',0,'intval');

        if (!empty($menu_id)) {

            if (!$detail = $this->menu_model->find($menu_id)) {
                $this->error('请选择要改变状态的' . self::CNAME);
            }
            $data['menu_id'] = $menu_id;
            $data['status']  = $detail['status'] ? 0 : 1 ;
            if ($this->menu_model->save($data) !== false) {
                $this->success(self::CNAME .'状态改变成功', U('index'));
            } else {
                $this->error(self::CNAME . '状态改变失败');
            }
        } else {
            $this->error('请选择要改变状态的' . self::CNAME);
        }
    }

    /**
     * 模块编辑
     */
    public function actionEdit() {
        $menu_pid = I('parent_id', 0, 'intval');
        if (IS_POST) {
            $oldlines  = I('post.oldlines', array(), 'trim');
            $newlines  = I('post.newlines', array(), 'trim');

            if (!empty($oldlines)) {
                foreach ($oldlines as $menu_id => $v) {
                    $v['parent_id'] = $menu_pid;
                    $v['menu_id']   = $menu_id;
                    $data = $this->menu_model->create($v);
                    if ($data) {
                        if ($this->menu_model->save($data) !== false) {

                            $detail = $this->menu_model->find($menu_id);

                            $app        = $v['app'];
                            $controller = $v['controller'];
                            $action     = $v['action'];
                            $name       = strtolower("$app/$controller/$action");
                            $menu_name  = $v['menu_name'];
                            $where      = array('rule_id' => $detail['rule_id']);

                            $rule_count = $this->authRule_model->where($where)->count();
                            if (empty($rule_count)) {
                                $id = $this->authRule_model->add(array(
                                    'name'      => $name,
                                    'module'    => $app,
                                    'type'      => 'admin_url',
                                    'rule_name' => $menu_name));
                                $this->menu_model->where(array('menu_id' => $id))
                                    ->save(array('rule_id' => $detail['rule_id']));
                            } else {
                                $this->authRule_model->where($where)->save(array(
                                    "name"      => $name,
                                    "module"    => $app,
                                    "type"      => "admin_url",
                                    "rule_name" => $menu_name
                                ));
                            }
                            //$this->success('编辑成功', U('index'));
                        } else {
                            //$this->error('编辑失败');
                        }
                    } else {
                        //$this->error($this->menu_model->getError());
                    }
                }
            }

            //新的行进行添加
            if (!empty($newlines)) {
                foreach ($newlines as $v) {
                    $v['parent_id'] = $menu_pid;
                    $data = $this->menu_model->create($v);
                    if ($data) {
                        $id = $this->menu_model->add($data);
                        if ($id) {
                            $app        = $v['app'];
                            $controller = $v['controller'];
                            $action     = $v['action'];
                            $name       = strtolower("$app/$controller/$action");
                            $menu_name  = $v['menu_name'];
                            $where      = array("name" => $name);
                            $rule_count = $this->authRule_model->where($where)->count();
                            if (empty($rule_count)) {
                                $rule_id = $this->authRule_model->add(array(
                                    "name"      => $name,
                                    "module"    => $app,
                                    "type"      => "admin_url",
                                    "rule_name" => $menu_name
                                ));
                                $this->menu_model->where(array('menu_id' => $id))
                                    ->save(array('rule_id' => $rule_id));
                            }
                            //$this->success('添加成功', U('index'));
                        } else {
                           //$this->error('添加失败');
                        }

                    } else {
                       // $this->error($this->menu_model->getError().print_r($v,true));
                    }
                }
            }
            $this->success('更新成功');
        } else {

            $this->assign('menus', $this->menu_model->fetchAll());
            $this->assign('parent_id', $menu_pid);
            $this->display();
        }
    }

    /**
     * 获取菜单树
     */
    private function _getMenuTree() {
        $menus = $this->menu_model->fetchAll();
        return x_get_tree($menus,'menu_id', 'parent_id', 'menu_name');
    }
}